import React, { Component } from "react";
import { Form, Input, Button, message, Divider, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import PropTypes from 'prop-types';
import "./index.less";
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};
const tailLayout = {
  wrapperCol: { offset: 4, span: 20 },
};

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}
export default class Account extends Component {

  constructor(props) {
    super(props);
    this.state = {
      fileList: ''
    };
  }

  componentDidMount() {
    this.getData();
  }

  getData = () => {
    this.get("/setting/get", "")
      .then((res) => {
        if (res.code === 200) {
          this.formRef2.current.setFieldsValue({
            name: res.data.name,
            subtitle: res.data.subtitle,
            detail: res.data.detail,
            site_name: res.data.site_name,
            upload: res.data.avatar ? [] : ''
          });
          this.setState({ img: res.data.avatar })
        }
      })
  };

  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }
  handleChange = async info => {
    getBase64(info.file, img =>
      this.setState({
        img,
      }),
    );
  }

  formRef = React.createRef();  // 密码修改
  formRef2 = React.createRef(); // 系统信息
  onFinish = (values) => {
    this.post("/admin/edit", {
      password: values.password,
      newpwd: values.newpwd,
      renewpwd: values.renewpwd
    }).then((data) => {
      if (data.code === 200) {
        message.success('修改成功，请重新登录', 1.5, () => {
          localStorage.removeItem('my-login-token');
          this.props.setLoginInfo({
            token: "",
            userInfo: {},
          });
          this.props.history.push({
            pathname: "/login",
          });
        })
      } else {
        message.error(data.msg || '修改失败，服务器异常')
      }
    })
  };

  onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  onFinish2 = (values) => {
    let data = { ...values, avatar: this.state.img };
    delete data.upload;
    this.post("admin/setting/edit", data).then((res) => {
      if (res.code === 200) {
        message.success('修改成功', 1.5)
      } else {
        message.error('修改失败', 1.5)
      }
    })
  }

  onReset = () => {
    this.formRef.current.resetFields();
  };
  onReset2 = () => {
    this.formRef2.current.resetFields();
  };

  render() {
    const fileList = this.state.fileList;
    const props = {
      onChange: this.handleChange,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      fileList,
    };
    return (
      <div className="account-container">
        <Divider plain orientation="left">管理员账户密码修改</Divider>
        <Form
          {...layout}
          name="basic"
          ref={this.formRef}
          initialValues={{ remember: true }}
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
        >

          <Form.Item
            label="旧密码"
            name="password"
            rules={[{ required: true, message: "请输入旧密码" }]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>

          <Form.Item
            label="新密码"
            name="newpwd"
            rules={[{ required: true, message: "请输入新密码" }]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>

          <Form.Item
            label="确认新密码"
            name="renewpwd"
            rules={[{ required: true, message: "请确认新密码" }]}
          >
            <Input.Password autoComplete="new-password" />
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              确认修改
            </Button>
            <Button htmlType="button" onClick={this.onReset} style={{ marginLeft: 8 }}>
              重置
            </Button>
          </Form.Item>
        </Form>

        <Divider plain orientation="left">系统信息维护</Divider>
        <Form
          {...layout}
          name="basic2"
          ref={this.formRef2}
          initialValues={{ remember: true }}
          onFinish={this.onFinish2}
          onFinishFailed={this.onFinishFailed}
        >
          <Form.Item
            label="作者名称"
            name="name"
            rules={[{ required: true, message: "请输入作者名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="网站名称"
            name="site_name"
            rules={[{ required: true, message: "请输入网站名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="个性签名"
            name="subtitle"
            rules={[{ required: true, message: "请输入个性签名" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="随便说两句吧"
            name="detail"
            rules={[{ required: true, message: "请输入随便说两句吧" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="upload"
            label="头像"
            rules={[{ required: false, message: "请上传头像" }]}
            valuePropName="fileList"
            getValueFromEvent={this.normFile}
          >
            <Upload maxCount={1} {...props} listType="picture" showUploadList={false}>
              {this.state.img ? <img className="preImg" src={this.state.img} alt="avatar" /> : <Button icon={<UploadOutlined />}>选择图片</Button>}
            </Upload>
          </Form.Item>


          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit">
              确认修改
            </Button>
            <Button htmlType="button" onClick={this.onReset2} style={{ marginLeft: 8 }}>
              重置
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}
Account.contextTypes = { store: PropTypes.object }